package com.example.food_contract_system.util;

import com.example.food_contract_system.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 照片上传方法
 * @author LiHaoyang
 * @date 2023/7/6  20:09
 **/
@RestController
@RequestMapping("/index")
public class UploadPictureVo extends BaseController {

    /**
     * 经销商注册,上传 营业执照 图片
     * @param image
     * @return
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile image){
        String fileName = image.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffixName;
        String filePath = getFolder("upload");

        try{
            File file = new File(getPhysicalPath(filePath)+"/"+fileName);
            image.transferTo(file);
            request.setAttribute("url",filePath+"/"+fileName);

            return R.ok().put("data",request.getAttribute("url"));
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }


    private String getFolder(String path) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        path += "/" + formater.format(new Date());
        File dir = new File(this.getPhysicalPath(path));
        if (!dir.exists()) {
            try {
                dir.mkdirs();
            } catch (Exception e) {
                return "";
            }
        }
        return path;
    }

    /**
     * 根据传入的虚拟路径获取物理路径
     *
     * @param path
     * @return
     */
    private String getPhysicalPath(String path) {
        String servletPath = this.request.getServletPath();
        String realPath = this.request.getSession().getServletContext()
                .getRealPath(servletPath);
        return new File(realPath).getParent() +"/" +path;
    }
}
